package com.shuoyue.ycgk.ui.questionbank.base;

import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import com.shuoyue.ycgk.base.BaseMvpFragment;
import com.shuoyue.ycgk.entity.QuestionSimple;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

public class BaseSimpleAdapter<T extends BaseMateriFragment,
        K extends BaseSimpleFragment>
        extends FragmentStatePagerAdapter {
    private BaseMvpFragment mCurrentFragment;
    List<QuestionSimple> mData;
    int totalQuestion;
    Class<K> kClass;  Class<T> tClass;


    public BaseSimpleAdapter(@NonNull FragmentManager fm,
                             List<QuestionSimple> mData,
                             int totalQuestion,
                             Class tClass,
                             Class kClass) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        if (mData != null) {
            this.mData = mData;
        } else {
            this.mData = new ArrayList<>();
        }
        this.totalQuestion = totalQuestion;
        this.tClass = tClass;
        this.kClass = kClass;
    }

    @NonNull
    @Override
    public BaseMvpFragment getItem(int position) {
        QuestionSimple questionSimple = mData.get(position);
        if (questionSimple.getQuestionType() != 10) {
            //不是填空题的,统一用选择题的模型
            try {
                K baseMateriFragment = kClass.newInstance();
                baseMateriFragment.init(questionSimple, totalQuestion);
                return baseMateriFragment;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
        return null;//填空题模型
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        mCurrentFragment = (BaseMvpFragment) object;
        super.setPrimaryItem(container, position, object);
    }


    public BaseMvpFragment getCurrentFragment() {
        return mCurrentFragment;
    }

    public List<QuestionSimple> getMyDate() {
        return mData;
    }


    private K getInstanceOfK() {
        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        Class<K> type = (Class<K>) superClass.getActualTypeArguments()[0];
        try {
            return type.newInstance();
        } catch (Exception e) {
            // Oops, no default constructor
            throw new RuntimeException(e);
        }
    }
}
